package com.powerunion.extjs.data;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.extjs.BasePara;
import com.powerunion.extjs.ListRange;
import com.powerunion.extjs.MetaData;
import com.powerunion.extjs.XmlParser;

public class GridDataLoader extends DbDataLoader {
	private HashMap suminfo;
	
	public GridDataLoader(BasePara paravo){
		super(paravo);
	} 
	
	public void wrapSql() throws Exception{
		XmlParser parser = new XmlParser();
		this.paravo.setXmlFileName("grid_sql_config.xml");
		parser.loadSql(this.paravo);
		this.paravo.addWhereSql();
		this.paravo.addGroupSql();
		this.paravo.addOrderSql();
	}
	
	
	public void collectToMap() {
		ArrayList al = null;
		HashMap map = null;
		String[] colNameArray = convert.contvertColumnName( this.paravo.getSql());
		al = new ArrayList();
		if (!rs.isEmpty()) {
			al = new ArrayList();
			for (Iterator it = rs.iterator(); it.hasNext();) {
				Map obj = (Map) it.next();
				
//				Object[] obj = null;
//				if(colNameArray.length==1){
//					obj = new Object[]{it.next()};
//				}else{
//					obj = (Object[]) it.next();
//				}
				map = new HashMap();
				for (int i = 0; i < colNameArray.length; i++) {
					String tag = colNameArray[i].toLowerCase();
					map.put(tag, obj.get(tag));
				}
				al.add(map);
			}
		}
		range = new ListRange();
		range.setData(al);
		range.setTotalSize(this.totalCount);
		this.setMetaData(colNameArray);
	}
	
	public int getTotalCount(String hql, Object params,String type) throws Exception {
		int total = 0;
		String msql="";
		try {
			if(hql.indexOf(" order by ")>0) hql = hql.replace(hql.substring(hql.indexOf(" order by ")), "");
			if(hql.indexOf("group by")>0) {
				msql=" from ( "+hql+" )";
			}else{
				msql = hql.substring(hql.lastIndexOf("from"));
			}
			String sumsql=paravo.getSumsql();
			if(null!=sumsql && !"".equals(sumsql)){
				hql = "select count(1) as count, "+sumsql+" " + msql;
				total = this.getSumInfo(hql, params, type);
			}else{
				hql = "select count(1) as count " + msql;
				QueryOperator query = new QueryOperator();
				query.setSql(hql);
				query = convert.getParams(query,  params);
				query.access();
				if (query.resultSetAvailable()) {
					RsDataSet rs = new RsDataSet(query.getSqlResultSet());
					if (rs.rowCount > 0) {
						total =rs.getFieldValueAsInteger("count").intValue();
					}
					rs.clearAll();
				}
			}
		} catch (Exception e) {
			throw new Exception("get total error-->"+e.getMessage(),e.getCause());
		} 
		return total;
	}	
	
	/**
	 * 汇总信息赋值
	 * @param hql
	 * @param params
	 * @param type
	 * @return
	 */
	private int getSumInfo(String hql, Object params,String type) throws Exception {
		QueryOperator query = new QueryOperator();
		int totalCount=0;
		try{
			query.setSql(hql);
			query = convert.getParams(query,  params);
			query.access();
			if (query.resultSetAvailable()) {
				rs = query.getSqlResultSet();
			}
			
		
			if (!rs.isEmpty()) {
				
				String[] colNameArray = convert.contvertColumnName( hql);
				for (Iterator it = rs.iterator(); it.hasNext();) {
					Object[] obj = null;
					if(colNameArray.length==1){
						obj = new Object[]{it.next()};
					}else{
						obj = (Object[]) it.next();
					}
					suminfo = new HashMap();
					for (int i = 0; i < colNameArray.length; i++) {
						
						if(i==0) {
							totalCount=(int) (Double.parseDouble(obj[i]+""));
							continue;
						}
						colNameArray[i] = colNameArray[i];//.toLowerCase();
						String tag = colNameArray[i];
						suminfo.put(tag, obj[i]);
					}
					break;
				}
			}
		}catch(Exception e){
			throw new Exception("get sumInfo error-->"+e.getMessage(),e.getCause());
		}
		
		return totalCount;
	}
	
	private void setMetaData(String[] colNameArray){
		ArrayList al = new ArrayList();
		HashMap map=null;
		for(int k=0;k<colNameArray.length;k++){
			map=new HashMap();
			map.put("name", colNameArray[k]);
			map.put("mapping", colNameArray[k]);
			
			al.add(map);
		}
		MetaData meta = new MetaData();
		meta.setFields(al);
		meta.setId(this.paravo.getRecordId());
		if(null!=suminfo){
			meta.setSumObject(suminfo); //合计信息
		}
		range.setMetaData(meta);
	}
}
